package com.fqgj.sentry.policy.server;

import com.fqgj.sentry.common.exception.BizException;
import com.fqgj.sentry.common.exception.enums.ErrorCodeEnums;
import com.fqgj.sentry.policy.client.ExecuteResultService;
import com.fqgj.sentry.policy.dao.PcExecuteResultDao;
import com.fqgj.sentry.policy.entity.PcExecuteResultEntity;
import com.fqgj.sentry.policy.enums.ExecutorDefaultResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by ykpbean kangping.ying@yuntu-inc.com
 *
 * @description
 * @create 2017-07-31 下午8:30
 */

@Service
public class ExecuteResultServiceImpl implements ExecuteResultService {


    @Autowired
    private PcExecuteResultDao executeResultDao;

    @Override
    public Long insertExecuteResult(PcExecuteResultEntity executeResultEntity) {
        checkExecuteResult(executeResultEntity.getPolicySetsId(), executeResultEntity.getResult());
        executeResultDao.insert(executeResultEntity);
        return executeResultEntity.getId();
    }

    @Override
    public List<PcExecuteResultEntity> selectExecuteResultList(Long policySetsId) {

        return executeResultDao.selectExecuteResultList(policySetsId);
    }

    @Override
    public PcExecuteResultEntity selectExecuteResultListByResult(Long policySetsId, ExecutorDefaultResultEnum executorResultEnum) {
        return executeResultDao.selectExecuteResultByResult(policySetsId, executorResultEnum.getResult());
    }

    @Override
    public PcExecuteResultEntity selectMaxLevelExecuteResult(Long policySetsId) {
        return executeResultDao.selectMaxLevelExecuteResultList(policySetsId);
    }

    @Override
    public Boolean deleteExecuteResult(Long id) {
        return executeResultDao.deleteByPrimaryKey(id) > 0;
    }

    @Override
    public Boolean updateExecuteResult(PcExecuteResultEntity executeResultEntity) {
        return executeResultDao.updateByPrimaryKey(executeResultEntity) > 0;
    }

    @Override
    public PcExecuteResultEntity findByExecutorResultId(Long resultId) {
        PcExecuteResultEntity executeResultEntity = executeResultDao.selectByPrimaryKey(resultId);
        return executeResultEntity;
    }

    private void checkExecuteResult(Long policySetsId, String result) {
        PcExecuteResultEntity executeResultEntity = executeResultDao.selectExecuteResultByResult(policySetsId, result);
        if (executeResultEntity != null) {
            throw new BizException(ErrorCodeEnums.policy_execute_result_is_exist_error);
        }
    }
}
